﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Reflection;
using System.Net;
using System.IO;

namespace GIVisualEditor.Updater
{
    public class SelfUpdateManager
    {
        public static string SoftwareUpdateScriptProviderUrl = @"http://www.improveMySkill.com/GIupdate/default.aspx";


        public static string GetUpdateActionScript()
        {
            // GIVisual - short app name in lowercase
            string appName = "giv", version = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                   os = Environment.OSVersion.ToString();
            string sUrl = string.Format("{0}?a={1}&v={2}&os={3}", SoftwareUpdateScriptProviderUrl, appName, version, os);
            WebRequest req = WebRequest.Create(sUrl);
            req.Method = "GET";
            req.Timeout = 120000; // 2 min should be enough
            Stream respStream =  req.GetResponse().GetResponseStream();
            StreamReader reader = new StreamReader(respStream);
            string sResult = reader.ReadToEnd();
            reader.Close();

            return sResult;
        }

        public static bool CheckAndUpgrade()
        {
            try
            {
                int desc = 0;
                if (Win32Helper.InternetGetConnectedState(out desc, 0))
                {
                    string sActionScript = GetUpdateActionScript();
                    bool bResult = TaskModel.TaskFactory.ExecuteUpgradeRequestResponse(sActionScript);

                    return bResult;
                }
            }
            catch (Exception ex)
            {
                int dummy = 100;// Log
            }

            return false;
        }

    }
}
